package com.wx.task;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 信号量测试
 * 在信号量模型中 存在
 * 1. 状态值（对外透明）
 * 2. 等待队列（对外透明）
 * 3. p 减少操作（对外可见）
 * 4. v 增加操作 （对外可见）
 * @author wang.xun
 * @date 2023/07/26
 */
@Slf4j
public class SemaphoreTest {
    Semaphore semaphore = new Semaphore(1);

    static int count = 0;
    void addCount(){
        try {
            semaphore.acquire();
            count++;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            semaphore.release();
        }

    }

    int getCount(){
        try {
            semaphore.acquire();
            return count;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            semaphore.release();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor= Executors.newFixedThreadPool(10);
        SemaphoreTest semaphoreTest = new SemaphoreTest();
        Runnable runnable = new Runnable(){

            @Override
            public void run() {
                semaphoreTest.addCount();
            }
        };

        for (int i = 0; i < 10000; i++) {


            executor.execute(runnable);
        }

        Thread.sleep(4000);
        log.info("count value is {}",new SemaphoreTest().getCount());

    }

}
